package org.mx.service.server.jmx;

import java.util.Date;
import java.util.List;

import org.mx.DateUtils;
import org.mx.service.server.CommServerConfigBean;
import org.mx.service.server.CommServerFactory;

/**
 * TCP/UDP服务器MXBean实现类
 * @author john.peng
 *
 */
public class CommServer implements CommServerMXBean {
	private boolean tcpEnabled, udpEnabled;
	private List<CommServerConfigBean.ServerConfig> tcpServers;
	private List<CommServerConfigBean.ServerConfig> udpServers;
	
	private long startedTime = -1L;
	private CommServerFactory commServerFactory;
	
	/**
	 * 构造函数
	 * @param configBean TCP/UDP服务器配置类
	 */
	public CommServer(CommServerConfigBean configBean) {
		super();
		if (configBean != null) {
			tcpEnabled = configBean.isTcpEnabled();
			tcpServers = configBean.getTcpServers();
			udpEnabled = configBean.isUdpEnabled();
			udpServers = configBean.getUdpServers();
		}
	}
	
	/**
	 * 设置服务器工程
	 * @param commServerFactory 服务器工厂
	 */
	public void setCommServerFactory(CommServerFactory commServerFactory) {
		this.commServerFactory = commServerFactory;
	}

	@Override
	public String getStartedTime() {
		return DateUtils.get23Date(new Date(startedTime));
	}



	/**
	 * 将运行持续时间转换为“#天#小时#分#秒”的格式。
	 * @param time 运行持续时间
	 * @return 时间描述
	 */
	private String format(long time) {
		int[] units = { 60, 60, 24 };
		int[] number = { 0, 0, 0, (int) (time / 24 / 3600) };
		time -= number[3] * 24 * 3600;
		String[] names = { "秒", "分", "小时", "天" };
		for (int index = 0; index < 3; index++) {
			number[index] = (int) (time % units[index]);
			time = (time - number[index]) / units[index];
		}
		StringBuffer sb = new StringBuffer();
		for (int index = 3; index >= 0; index--) {
			if (number[index] > 0) {
				sb.append(number[index]);
				sb.append(names[index]);
			}
		}
		return sb.toString();
	}

	@Override
	public String getElapseTime() {
		long time = System.currentTimeMillis() - startedTime;
		time = Math.max(time, 0);
		return format(time / 1000);
	}

	@Override
	public void startServer() throws Exception {
		if (commServerFactory != null) {
			commServerFactory.init();
		}
	}

	@Override
	public void stopServer() throws Exception {
		if (commServerFactory != null) {
			commServerFactory.destroy();
		}
	}

	@Override
	public void restartServer() throws Exception {
		stopServer();
		startServer();
	}

	@Override
	public boolean isTcpEnabled() {
		return tcpEnabled;
	}

	@Override
	public List<CommServerConfigBean.ServerConfig> getTcpServers() {
		return tcpServers;
	}

	@Override
	public boolean isUdpEnabled() {
		return udpEnabled;
	}

	@Override
	public List<CommServerConfigBean.ServerConfig> getUdpServers() {
		return udpServers;
	}
}
